package actions;

import java.sql.SQLException;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
import model.UniversityModel;

public class DegreeAction extends Action {

	private static final boolean DEBUG = true;
	//private static final int UNKNOWN = -1;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
	
		// initialize counter for degree to keep count number of degrees user is entering
		int degrees_count  = (Integer) request.getSession().getAttribute("degrees_count");
		request.getSession().setAttribute("degrees_count", degrees_count+1);
		
		// put list of universities into a vector
		RowSet rset = UniversityModel.getLocations();

		Vector<String> locations_1 = new Vector<String>();
		Vector<String> locations_2 = new Vector<String>();
		Vector<String> locations_3 = new Vector<String>();

		int count = 0;
		
		try {
			while (rset.next()) {
				
				count = (count + 1)%3;
				
				switch(count) {
					case 1:
						locations_1.add(rset.getString("location"));
						break;
					case 2:
						locations_2.add(rset.getString("location"));
						break;
					default:
						locations_3.add(rset.getString("location"));
						break;
				}
			}
			
			if (locations_2.size() < locations_1.size()) {
				locations_2.add("");
			}
			
			if (locations_3.size() < locations_1.size()) {
				locations_3.add("");
			}
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
		}
		
		request.setAttribute("locations_1", locations_1);
		request.setAttribute("locations_2", locations_2);
		request.setAttribute("locations_3", locations_3);
		
		return mapping.findForward("success");
	}
	
}
